package interceptor

import (
	"context"
	"log"
	"protobuf-learn/proto"
	"time"

	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type Service struct {
	proto.UnimplementedInterceptorServiceServer
}

func (s *Service) LongRuning(ctx context.Context, req *proto.LongRuningRequest) (*proto.LongRuningResponse, error) {
	ticker := time.NewTicker(time.Second * 5)
	select {
	case <-ticker.C:
		log.Println("finished waiting, not end request successfully")
	case <-ctx.Done():
		log.Println("context cancelled")
		return nil, ctx.Err()
	}

	return &proto.LongRuningResponse{}, nil
}

func (s *Service) Protected(ctx context.Context, req *proto.ProtectedRequest) (*proto.ProtectedResponse, error) {
	userId, ok := ctx.Value(userIdCtxKey).(string)
	if !ok {
		return nil, status.Error(codes.FailedPrecondition, "user id missing from context")
	}

	return &proto.ProtectedResponse{
		UserId: userId,
	}, nil
}
